package com.syq.play.db.entity;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.util.Log;

import com.syq.play.R;
import com.syq.play.db.ModeManagerBase;
import com.syq.play.id3.Id3Util;
import com.syq.play.model.FolderModel;
import com.syq.play.model.MediaModel;
import com.syq.play.util.FileScanTool;
import com.syq.play.util.MyStringUtil;

/**
 * 设置歌曲数据表类
 * 
 * @author ShiYiqiong
 * 
 */
public class SongManager extends ModeManagerBase {
	private Context context;

	private static SongManager instance = null;

	private SongManager() {
	}

	public static SongManager getInstance() {
		if (instance == null)
			instance = new SongManager();
		return instance;
	}
	/**
	 * 插入一条歌曲数据
	 * @param media
	 */
	public void insetSongData(MediaModel media) {
		if (!haveSongData(media.getMediaData())) {
			ContentValues values = new ContentValues();
			if (media.getMediaTitle() != null) {
				values.put(SongEntity.TITLE, media.getMediaTitle());
			}
			if (media.getMediaAlbum() != null) {
				values.put(SongEntity.ALBUM, media.getMediaAlbum());
			}
			if (media.getMediaArtist() != null) {
				values.put(SongEntity.ARTIST, media.getMediaArtist());
			}
			if (media.getMediaData() != null) {
				String data=media.getMediaData();
				values.put(SongEntity.DATA, data);
				values.put(SongEntity.FOLDER, data.substring(0, data.lastIndexOf("/")));
				values.put(SongEntity.DISPLAY_NAME, data.substring(data.lastIndexOf("/")+1));
				if(media.getMediaTitle() == null || media.getMediaTitle().equals("未知")){
					values.put(SongEntity.TITLE, data.substring(data.lastIndexOf("/")+1));
				}
			}
			if (media.getMediaDuration() != null) {
				values.put(SongEntity.DURATION, media.getMediaDuration());
			}
			if (media.getMediaSize() != 0) {
				values.put(SongEntity.SIZE, media.getMediaSize());
			}
			_db.insert(SongEntity.SONG_TABLE, null, values);
		}
	}

	/**
	 * 插入系统歌曲到歌曲数据表
	 * 
	 * @param list
	 */
	public void insertAllSongData(List<HashMap<String, Object>> list) {
		for (HashMap<String, Object> item : list) {
			String data = "" + item.get(SongEntity.DATA);
			if (!haveSongData(data)) {
				ContentValues values = new ContentValues();
				for (String key : item.keySet()) {
					values.put(key, "" + item.get(key));
				}
				_db.insert(SongEntity.SONG_TABLE, null, values);
			}
		}
	}

	/**
	 * 根据歌曲路径判断歌曲数据表是否存在个歌曲
	 * 
	 * @param data
	 * @return
	 */
	private boolean haveSongData(String data) {
		String selection = SongEntity.DATA + " =? ";
		String[] selectionArgs = new String[] { data };
		Cursor cursor = _db.query(SongEntity.SONG_TABLE,
				new String[] { SongEntity.DATA }, selection, selectionArgs,
				null, null, null);
		if (cursor.getCount() > 0) {
			if (!cursor.isClosed()) {
				cursor.close();
			}
			return true;
		}
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return false;
	}

	/**
	 * 获取所有歌曲数量
	 * 
	 * @return
	 */
	public int getAllSongCount() {
		Cursor cursor = _db.query(SongEntity.SONG_TABLE,
				new String[] { SongEntity._ID }, null, null, null, null, null);
		int count = cursor.getCount();
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return count;
	}

	/**
	 * 获取所有歌手数量
	 * 
	 * @return
	 */
	public int getArtistCount() {
		Cursor cursor = _db.query(SongEntity.SONG_TABLE,
				new String[] { "distinct " + SongEntity.ARTIST }, null, null,
				null, null, null);
		int count = cursor.getCount();
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return count;
	}

	/**
	 * 获取所有专辑数量
	 * 
	 * @return
	 */
	public int getAlbumtCount() {
		Cursor cursor = _db.query(SongEntity.SONG_TABLE,
				new String[] { "distinct " + SongEntity.ALBUM }, null, null,
				null, null, null);
		int count = cursor.getCount();
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return count;
	}

	/**
	 * 获取所有歌手数量
	 * 
	 * @return
	 */
	public int getFolderCount() {
		Cursor cursor = _db.query(SongEntity.SONG_TABLE,
				new String[] { "distinct " + SongEntity.FOLDER }, null, null,
				null, null, null);
		int count = cursor.getCount();
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return count;
	}

	/**
	 * 获取我的最爱歌曲数量
	 * 
	 * @return
	 */
	public int getFavoriteSongCount() {
		String selection = SongEntity.PLAY_COUNT + " > ?";
		String[] selectionArgs = new String[] { "0" };
		Cursor cursor = _db.query(SongEntity.SONG_TABLE,
				new String[] { SongEntity._ID }, selection, selectionArgs,
				null, null, null);
		int count = cursor.getCount();
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return count;
	}

	/**
	 * 获取最近播放歌曲数量
	 * 
	 * @return
	 */
	public int getRecentSongCount() {
		String selection = SongEntity.PLAY_TIME + " > ?";
		String[] selectionArgs = new String[] { "-1" };
		Cursor cursor = _db.query(SongEntity.SONG_TABLE,
				new String[] { SongEntity._ID }, selection, selectionArgs,
				null, null, null);
		int count = cursor.getCount();
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return count;
	}

	/**
	 * 根据歌手获取所有歌曲数量
	 * 
	 * @return
	 */
	public int getCountFromArtist(String artist) {
		String selection = SongEntity.ARTIST + " =? ";
		String[] selectionArgs = new String[] { artist };
		Cursor cursor = _db.query(SongEntity.SONG_TABLE,
				new String[] { SongEntity._ID }, selection, selectionArgs,
				null, null, null);
		int count = cursor.getCount();
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return count;
	}

	/**
	 * 根据专辑获取所有歌曲数量
	 * 
	 * @return
	 */
	public int getCountFromAlbum(String album) {
		String selection = SongEntity.ALBUM + " =? ";
		String[] selectionArgs = new String[] { album };
		Cursor cursor = _db.query(SongEntity.SONG_TABLE,
				new String[] { SongEntity._ID }, selection, selectionArgs,
				null, null, null);
		int count = cursor.getCount();
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return count;
	}

	/**
	 * 根据歌曲文件夹获取所有歌曲数量
	 * 
	 * @return
	 */
	public int getCountFromFolder(String folder) {
		String selection = SongEntity.FOLDER + " =? ";
		String[] selectionArgs = new String[] { folder };
		Cursor cursor = _db.query(SongEntity.SONG_TABLE,
				new String[] { SongEntity._ID }, selection, selectionArgs,
				null, null, null);
		int count = cursor.getCount();
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return count;
	}

	/**
	 * 获取所有歌手
	 * 
	 * @return
	 */
	public List<FolderModel> getAllArtist() {
		List<FolderModel> resut = null;
		Cursor cursor = _db.query(SongEntity.SONG_TABLE,
				new String[] { "distinct " + SongEntity.ARTIST }, null, null,
				null, null, null);
		if (cursor.moveToFirst()) {
			resut = new ArrayList<FolderModel>();
			do {
				FolderModel folder = new FolderModel();
				String name = cursor.getString(cursor
						.getColumnIndex(SongEntity.ARTIST));
				folder.setFolderName(name);
				folder.setFileNum(getCountFromArtist(name) + "首歌曲");
				resut.add(folder);
			} while (cursor.moveToNext());
		}
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return resut;
	}
	

	/**
	 * 获取所有专辑
	 * 
	 * @return
	 */
	public List<FolderModel> getAllAlbum() {
		List<FolderModel> resut = null;
		Cursor cursor = _db.query(SongEntity.SONG_TABLE,
				new String[] { "distinct " + SongEntity.ALBUM }, null, null,
				null, null, null);
		if (cursor.moveToFirst()) {
			resut = new ArrayList<FolderModel>();
			do {
				FolderModel folder = new FolderModel();
				String name = cursor.getString(cursor
						.getColumnIndex(SongEntity.ALBUM));
				folder.setFolderName(name);
				folder.setFileNum(getCountFromAlbum(name) + "首歌曲");
				resut.add(folder);
			} while (cursor.moveToNext());
		}
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return resut;
	}

	/**
	 * 获取所有歌手
	 * 
	 * @return
	 */
	public List<FolderModel> getAllFolder() {
		List<FolderModel> resut = null;
		Cursor cursor = _db.query(SongEntity.SONG_TABLE,
				new String[] { "distinct " + SongEntity.FOLDER }, null, null,
				null, null, null);
		if (cursor.moveToFirst()) {
			resut = new ArrayList<FolderModel>();
			do {
				FolderModel folder = new FolderModel();
				String name = cursor.getString(cursor
						.getColumnIndex(SongEntity.FOLDER));
				folder.setFolderName(name);
				folder.setFileNum(getCountFromFolder(name) + "首歌曲");
				resut.add(folder);
			} while (cursor.moveToNext());
		}
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return resut;
	}

	/**
	 * 获取所有歌曲
	 * 
	 * @return
	 */
	public List<MediaModel> getAllSong() {
		List<MediaModel> resut = null;
		Cursor cursor = _db.query(SongEntity.SONG_TABLE, null, null, null,
				null, null, null);
		if (cursor.moveToFirst()) {
			resut = new ArrayList<MediaModel>();
			do {
				int id = cursor.getInt(cursor.getColumnIndex(SongEntity._ID));
				String artist = cursor.getString(cursor
						.getColumnIndex(SongEntity.ARTIST));
				String data = cursor.getString(cursor
						.getColumnIndex(SongEntity.DATA));
				String title = cursor.getString(cursor
						.getColumnIndex(SongEntity.TITLE));
				long duration = cursor.getLong(cursor
						.getColumnIndex(SongEntity.DURATION));
				MediaModel media = new MediaModel();
				media.setMediaId(id);
				media.setMediaArtist(artist);
				media.setMediaData(data);
				media.setMediaTitle(title);
				media.setMediaDuration(MyStringUtil
						.formatLongToTimeStr(duration));
				resut.add(media);
			} while (cursor.moveToNext());
		}
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return resut;
	}

	/**
	 * 获取所有我的最爱歌曲，按播放次数降序排列
	 * 
	 * @return
	 */
	public List<MediaModel> getAllFavoriteSong() {
		List<MediaModel> resut = null;
		String selection = SongEntity.PLAY_COUNT + " > ?";
		String[] selectionArgs = new String[] { "0" };
		Cursor cursor = _db.query(SongEntity.SONG_TABLE, null, selection,
				selectionArgs, null, null, SongEntity.PLAY_COUNT+" desc ");
		if (cursor.moveToFirst()) {
			resut = new ArrayList<MediaModel>();
			do {
				int id = cursor.getInt(cursor.getColumnIndex(SongEntity._ID));
				String artist = cursor.getString(cursor
						.getColumnIndex(SongEntity.ARTIST));
				String data = cursor.getString(cursor
						.getColumnIndex(SongEntity.DATA));
				String title = cursor.getString(cursor
						.getColumnIndex(SongEntity.TITLE));
				long duration = cursor.getLong(cursor
						.getColumnIndex(SongEntity.DURATION));
				long playCount=cursor.getLong(cursor
						.getColumnIndex(SongEntity.PLAY_COUNT));
				MediaModel media = new MediaModel();
				media.setMediaId(id);
				media.setMediaArtist(artist);
				media.setMediaData(data);
				media.setMediaTitle(title);
				media.setMediaDuration(MyStringUtil
						.formatLongToTimeStr(duration));
				media.setPlayCount(playCount);
				resut.add(media);
			} while (cursor.moveToNext());
		}
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return resut;
	}

	/**
	 * 获取所有最近播放歌曲
	 * 
	 * @return
	 */
	public List<MediaModel> getAllRecentSong() {
		List<MediaModel> resut = null;
		String selection = SongEntity.PLAY_TIME + " > ?";
		String[] selectionArgs = new String[] { "-1" };
		Cursor cursor = _db.query(SongEntity.SONG_TABLE, null, selection,
				selectionArgs, null, null, SongEntity.PLAY_TIME+" desc ");
		if (cursor.moveToFirst()) {
			resut = new ArrayList<MediaModel>();
			do {
				int id = cursor.getInt(cursor.getColumnIndex(SongEntity._ID));
				String artist = cursor.getString(cursor
						.getColumnIndex(SongEntity.ARTIST));
				String data = cursor.getString(cursor
						.getColumnIndex(SongEntity.DATA));
				String title = cursor.getString(cursor
						.getColumnIndex(SongEntity.TITLE));
				long duration = cursor.getLong(cursor
						.getColumnIndex(SongEntity.DURATION));
				long playTime=cursor.getLong(cursor
						.getColumnIndex(SongEntity.PLAY_TIME));
				MediaModel media = new MediaModel();
				media.setMediaId(id);
				media.setMediaArtist(artist);
				media.setMediaData(data);
				media.setMediaTitle(title);
				media.setMediaDuration(MyStringUtil
						.formatLongToTimeStr(duration));
				media.setPlayTime(playTime);
				resut.add(media);
			} while (cursor.moveToNext());
		}
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return resut;
	}
	/**
	 * 根据Key获取歌曲信息
	 * 
	 * @return
	 */
	public List<MediaModel> getMediaFromKey(String selection, String key) {
		List<MediaModel> resut = null;
		Cursor cursor = _db.query(SongEntity.SONG_TABLE, null, selection+" =? "
				, new String[]{key}, null, null, null);
		if (cursor.moveToFirst()) {
			resut = new ArrayList<MediaModel>();
			do {
				int id = cursor.getInt(cursor.getColumnIndex(SongEntity._ID));
				String artist = cursor.getString(cursor
						.getColumnIndex(SongEntity.ARTIST));
				String data = cursor.getString(cursor
						.getColumnIndex(SongEntity.DATA));
				String title = cursor.getString(cursor
						.getColumnIndex(SongEntity.TITLE));
				long duration = cursor.getLong(cursor
						.getColumnIndex(SongEntity.DURATION));
				MediaModel media = new MediaModel();
				media.setMediaId(id);
				media.setMediaArtist(artist);
				media.setMediaData(data);
				media.setMediaTitle(title);
				media.setMediaDuration(MyStringUtil
						.formatLongToTimeStr(duration));
				resut.add(media);
			} while (cursor.moveToNext());
		}
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return resut;
	}
	public void addPlayedSong(String data){
		Cursor cursor = _db.query(SongEntity.SONG_TABLE, null
				,SongEntity.DATA+" =? ", new String[]{data}, null, null, null, null);
		if (cursor.moveToFirst()) {
			String id=cursor.getString(cursor
					.getColumnIndex(SongEntity._ID));
			String audioId=cursor.getString(cursor
					.getColumnIndex(SongEntity.AUDIO_ID));
			String displayName=cursor.getString(cursor
					.getColumnIndex(SongEntity.DISPLAY_NAME));
			String size=cursor.getString(cursor
					.getColumnIndex(SongEntity.SIZE));
			String artist = cursor.getString(cursor
					.getColumnIndex(SongEntity.ARTIST));
			String album=cursor.getString(cursor
					.getColumnIndex(SongEntity.ALBUM));
			String folder=cursor.getString(cursor
					.getColumnIndex(SongEntity.FOLDER));
			String title = cursor.getString(cursor
					.getColumnIndex(SongEntity.TITLE));
			long duration = cursor.getLong(cursor
					.getColumnIndex(SongEntity.DURATION));
			Long playCount=cursor.getLong(cursor
					.getColumnIndex(SongEntity.PLAY_COUNT))+1;
			
			ContentValues values=new ContentValues();
			values.put(SongEntity._ID, id);
			values.put(SongEntity.ALBUM, album);
			values.put(SongEntity.ARTIST, artist);
			values.put(SongEntity.AUDIO_ID, audioId);
			values.put(SongEntity.DATA, data);
			values.put(SongEntity.TITLE, title);
			values.put(SongEntity.DISPLAY_NAME, displayName);
			values.put(SongEntity.DURATION, duration);
			values.put(SongEntity.FOLDER, folder);
			values.put(SongEntity.PLAY_COUNT, playCount);
			values.put(SongEntity.SIZE, size);
			values.put(SongEntity.PLAY_TIME, Calendar.getInstance().getTimeInMillis());
			_db.update(SongEntity.SONG_TABLE, values, SongEntity.DATA+" =? ", new String[]{data});
		}
		
	}
	
	/**
	 * 删除数据库中，在SD卡上不存在的个歌曲数据
	 */
	public void delInexistentSong(){
		Cursor cursor = _db.query(SongEntity.SONG_TABLE, new String[]{ SongEntity.DATA }, null, null,
				null, null, null);
		if (cursor.moveToFirst()) {
			do {
				String data = cursor.getString(cursor
						.getColumnIndex(SongEntity.DATA));
				//如果该路径上不存在该文件，从数据库中删除该条数据
				if(!FileScanTool.haveFile(data)){
					_db.delete(SongEntity.SONG_TABLE, SongEntity.DATA+" =? ", new String[]{data});
				}
			} while (cursor.moveToNext());
		}
		if (!cursor.isClosed()) {
			cursor.close();
		}
	}
	public Bitmap getSongIcon(String selection, String selectionArgs ){
		Bitmap bitmap=null;
		Cursor cursor = _db.query(SongEntity.SONG_TABLE, new String[]{ SongEntity.DATA }
			, selection+" =? ", new String[]{ selectionArgs },
			 null, null, null);
		if (cursor.moveToFirst()) {
			do {
				String data = cursor.getString(cursor
						.getColumnIndex(SongEntity.DATA));
				bitmap=Id3Util.getMp3Icon(data);
				if(bitmap!=null){
					break;
				}
			} while (cursor.moveToNext());
		}
		if (!cursor.isClosed()) {
			cursor.close();
		}
		
		return bitmap;
	}
}
